package edu.hunan.cxb18.service.Impl;

import edu.hunan.cxb18.dao.AccountDao;
import edu.hunan.cxb18.dao.BookDao;
import edu.hunan.cxb18.dao.BookStockDao;
import edu.hunan.cxb18.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author chenheng
 * @create 2020-03-27 8:56
 */
@Service
@Transactional(readOnly = false ,isolation = Isolation.DEFAULT)
public class BookServiceImpl implements BookService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BookStockDao bookStockDao;
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private BookDao bookDao;
    @Override
    public void buyBook(String isbn, String username, int nums) throws Exception {
        String sql = "";
        Object[] args = {};
        //1查询书的库存
        int stock = bookStockDao.queryByIsbn(isbn);
        //判断是否符合要求
        if (stock<nums){
            throw new RuntimeException("库存不足");
        }
        //2查询账户的money
        double money = accountDao.queryBalance(username);
        //3查询书的价格
        double price = bookDao.queryByIsban(isbn);
        if (money<price*nums){
            throw new RuntimeException("金钱不够");
        }
        //4更新库存
        bookStockDao.updateStock(isbn,nums);

        if(2>1){
            throw new Exception("突然冒出的问题。");
        }
        //5更新账户
        accountDao.updateBalance(username,price*nums);
    }
}
